package wwj;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import wwj.reader.CsvReader;
import wwj.reader.TabReader;

/*
 *  hadoop jar /home/hadoop/桌面/boot.jar UsersMatrixItem /work/output/BookLike/1/part-r-00000 /work/output/UsersMatrixItem/8
 */
public class UsersMatrixItem {

	public static class MMapper extends
			Mapper<Object, Text, Text, Text> {

		public void map(Object key, Text value, Context context)
				throws IOException, InterruptedException {
			List<String> list = TabReader
					.readLine(value.toString());
			context.write(new Text(list.get(0)), new Text(list.get(1)));
		}
	}

	public static class MReducer extends
			Reducer<Text, Text, Text, IntWritable> {

		public void reduce(Text key, Iterable<Text> values,
				Context context) throws IOException,
				InterruptedException {
			
			List<String> list=new ArrayList<String>();
			for(Text val:values){
				list.add(val.toString());
			}
			for (int i=0;i<list.size();i++) {
				for (int j=0;j<list.size();j++) {
					  if(i<j){
						  if(list.get(i).toString().compareTo(list.get(j))<0) 
							  context.write(new Text(list.get(i)+"\t"+list.get(j)),new IntWritable(1));
						  else 
							  context.write(new Text(list.get(j)+"\t"+list.get(i)),new IntWritable(1));
					  }
					  
				}
			}
			

		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		String[] otherArgs = args;
		if (otherArgs.length < 2) {
			System.err.println("Usage:  <in> [<in>...] <out>");
			System.exit(2);
		}
		Job job = new Job(conf, "UsersMatrixItem");
		job.setJarByClass(UsersMatrixItem.class);
		 
		job.setMapperClass(MMapper.class);

		job.setReducerClass(MReducer.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		for (int i = 0; i < otherArgs.length - 1; ++i) {
			FileInputFormat.addInputPath(job,
					new Path(otherArgs[i]));
		}
		FileOutputFormat.setOutputPath(job, new Path(
				otherArgs[otherArgs.length - 1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}
